<?php
define('Feie_User', 'koyshe@gmail.com');
define('Feie_Ukey', 'Rz8t3Jb2hasqafFW');
define('Feie_Url', 'http://api.feieyun.cn/Api/Open/');
define('Feie_Sn', 920516015);

function feie_post($data) {
	$data['user'] = Feie_User;
	$data['stime'] = time();
	$data['sig'] = sha1($data['user'].Feie_Ukey.$data['stime']);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, Feie_Url);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HEADER, false);
	$result = curl_exec($ch);
	curl_close($ch);
	return json_decode($result, true);
}

function feie_print($info) {
	global $db;
	$info_list = $db->pe_selectall('orderdata', array('order_id'=>$info['order_id']));
	$data['apiname'] = 'Open_printMsg';
	$data['sn'] = Feie_Sn;
	$data['content'] .= "订单编号：{$info['order_id']}<BR>";
	$data['content'] .= "下单时间：".pe_date($info['order_atime'])."<BR>";
	$data['content'] .= "用户姓名：{$info['user_tname']}<BR>";
	$data['content'] .= "联系电话：{$info['user_phone']}<BR>";
	$data['content'] .= "收货地址：{$info['user_address']}<BR>";
	$data['content'] .= "<BOLD>名称　　　　　 单价  数量  金额</BOLD><BR>";
	$data['content'] .= '--------------------------------<BR>';
	foreach($info_list as $k=>$v) {
		$order_num += $v['product_num'];
		$product_name = feie_jslen($v['product_name'], 5.5);
		$product_money = feie_jslen($v['product_money'], 3);
		$product_num = feie_jslen($v['product_num'], 3);
		$product_allmoney = feie_jslen($v['product_allmoney'], 3);
		foreach ($product_name as $kk=>$vv) {
			if ($kk == 0) {
				$data['content'] .= "{$vv}  {$product_money[0]} {$product_num[0]} {$product_allmoney[0]}<BR>";			
			}
			else {
				$data['content'] .= "{$vv}<BR>";			
			}
		}
	}
	$data['content'] .= '--------------------------------<BR>';
	$data['content'] .= "总数：{$order_num}件<BR>";
	$data['content'] .= "总计：{$info['order_money']} 元";
	$json = feie_post($data);
	if ($json['msg'] == 'ok') {
		$sql_set['printlog_state'] = 'success';
		$code = 1;
		$msg = '打印成功';
	}
	else {
		$sql_set['printlog_state'] = 'error';
		$sql_set['printlog_error'] = $json['msg'];
		$code = 0;
		$msg = $json['msg'];
	}
	$sql_set['order_id'] = $info['order_id'];
	$sql_set['printlog_atime'] = time();
	$db->pe_insert('order_printlog', pe_dbhold($sql_set));
	return array('code'=>$code, 'msg'=>$msg);
}

function feie_jslen($name, $length = 5.5) {
	$name_arr = array();
	$name = preg_split('/(?<!^)(?!$)/u', $name);
	foreach ($name as $v) {
		if (strlen($v) == 3) {
			$last_length = $now_length += 1;	
		}
		else {
			$last_length = $now_length += 0.5;		
		}
		$str .= $v;
		if ($now_length >= $length) {
			$name_arr[] = $str;
			$str = '';
			$now_length = 0;
		}
	}
	if ($now_length) {
		$name_arr[] = $str;	
	}
	//计算最后一行的长度，不满则补空格占位
	if (intval($length - $last_length) > 0) {
		$name_arr[count($name_arr)-1] .= str_repeat(' ', intval($length - $last_length));
	}
	return $name_arr;
}
?>